import React from "react";
import SparkMD5 from 'spark-md5'
import {Breadcrumb, Button, Col, message, Popover, Radio, Row, Space, Tooltip, Upload, Input} from "antd";
import {FolderAddOutlined, ReloadOutlined, SwapOutlined, UploadOutlined, HomeOutlined} from "@ant-design/icons";
import {asyncTryUpload, asyncUploadToken} from "../../api/middle/centerContent";
import '../../assets/center/MiddleHeader.css';

export default class MiddleHeader extends React.PureComponent{
    constructor(props) {
        super(props);
        this.auth = '';
    };
    onBack = (index)=>{
        return ()=>{
            this.props.onBack(this.props.directory.slice(0,index));
        }
    }
    computeHash = async function (file) {
        return new Promise((resolve, reject) => {
            let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
                chunkSize = 2097152,                             // Read in chunks of 2MB
                chunks = Math.ceil(file.size / chunkSize),
                currentChunk = 0,
                spark = new SparkMD5.ArrayBuffer(),
                fileReader = new FileReader();

            fileReader.onload = function (e) {
                console.log('read chunk nr', currentChunk + 1, 'of', chunks);
                spark.append(e.target.result);                   // Append array buffer
                currentChunk++;

                if (currentChunk < chunks) {
                    loadNext();
                } else {
                    console.log('finished loading');
                    console.info('computed hash', spark.end());  // Compute hash
                    resolve(spark.end());
                }
            };

            fileReader.onerror = function () {
                console.warn('oops, something went wrong.');
                reject('hash获取失败');
            };

            function loadNext() {
                const start = currentChunk * chunkSize,
                    end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

                fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
            }

            loadNext();
        })}

    // componentDidUpdate(prevProps, prevState, snapshot) {
    //     if (prevProps.directory !== this.props.directory) {
    //         this.setState({directory: this.props.directory});
    //     }
    // }
    uploadProps = {
        action: '/v1/file/upload',
        data: {
            auth: this.auth,                     //jwt
        },
        method: "post",
        multiple: true,
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        //name:""                        //文件参数名
        async beforeUpdate(file) {
            try {
                //hash
                const hash = await this.computeHash(file);
                console.log(`hash获取成功`);
                //token
                const [{msg}] = await asyncUploadToken({
                    file_name: file.name
                });
                console.log(`token获取成功`);
                this.auth = msg
                //快传
                const [response] = await asyncTryUpload({
                    auth: this.auth,
                    hash
                });
                if (response.msg)   //？？如果hash校验存在
                {
                    message.success(`文件快传成功`);
                    return false;
                } else
                    return true;
            } catch (e) {
                message.error(`上传发生错误：${e}`);
                return false;
            }
        }
    };
    sortPopoverProps = {
        content: (<Radio.Group defaultValue={1} onChange={this.props.onSort}>
            <Space direction="vertical">
                <Radio value={1}>默认排序</Radio>
                <Radio value={2}>文件名</Radio>
                <Radio value={3}>上传时间</Radio>
            </Space>
        </Radio.Group>),
        trigger: "click",
        placement: "bottomRight"
    };
    upLoadPopoverProps = {
        content: (<Upload {...this.uploadProps}>
            <Button>选择文件</Button>
        </Upload>),
        trigger: 'click',
        placement: 'bottomRight'
    };
    render() {
        return (
                <Row align="middle" className='headerCenter'>
                    <Col className='directoryBar' span={16}>
                        <Breadcrumb style={{overflowX :"auto", whiteSpace:"nowrap"}}>
                            <Breadcrumb.Item>
                                <a onClick={this.onBack(0)}><HomeOutlined/></a>
                            </Breadcrumb.Item>
                            {this.props.directory.map((item, index)=>
                                    <Breadcrumb.Item><a onClick={this.onBack(index+1)}>{item}</a></Breadcrumb.Item>
                                ,this)}
                        </Breadcrumb>
                    </Col>
                    <Col span={4}>
                        <Input.Search allowClear enterButton onSearch={this.props.onSearch}/>
                    </Col>
                    <Col className={'buttonBar'} span={4}>
                        <Row justify='space-around'>
                            <Col className={'uploadButton'}>
                                <Tooltip title="上传文件" placement='top'>
                                    <Popover {...this.upLoadPopoverProps}>
                                        <Button
                                            icon={<UploadOutlined/>}
                                            type="primary"
                                            shape='circle'/>
                                    </Popover>
                                </Tooltip>
                            </Col>
                            <Col className={'refreshButton'}>
                                <Tooltip title="刷新" placement="topLeft">
                                    <Button onClick={this.props.onRefresh} icon={<ReloadOutlined />}/>
                                </Tooltip>
                            </Col>
                            <Col className={'createFolderButton'}>
                                <Tooltip title="新建文件夹" placement="top">
                                    <Button onClick={this.props.onCreatFolder} icon={<FolderAddOutlined />}/>
                                </Tooltip>
                            </Col>
                            <Col className={'sortButton'}>
                                <Tooltip title="排序方式" placement="topRight">
                                    <Popover {...this.sortPopoverProps}>
                                        <Button icon={<SwapOutlined rotate={90}/>}/>
                                    </Popover>
                                </Tooltip>
                            </Col>
                        </Row>
                    </Col>
                </Row>)
    }
}